//IPC
const { ipcMain, BrowserWindow } = require("electron");
const { AdsorbWindow } = require("../components/adsorbWindow");
const path = require("node:path");

//本窗口
let window = undefined;

//工具箱窗口
let toolWindow = undefined;

//本窗口句柄
let windowHandler = undefined;

//标题栏句柄 目前用于监听拖拽缩小，反馈unmaximize图标变化
let tBarHandler = undefined;

const { exec } = require("child_process");

function runPaddleOCR(imagePath) {
	return new Promise((resolve, reject) => {
		//python python/paddle_ocr.py
		exec(
			`python ${path.join(
				__dirname,
				"../../",
				"python/paddle_ocr.py"
			)} "${imagePath}"`,
			(error, stdout) => {
				if (error) reject(error);
				else resolve(JSON.parse(stdout).text);
			}
		);
	});
}

module.exports = () => {
	//异步：初始化句柄
	ipcMain.on("IMGEDIT-INIT", (event, arg) => {
		windowHandler = event;
	});

	//异步：初始化窗口标题栏句柄
	ipcMain.on("IMGEDIT-BAR-INIT", (event, arg) => {
		window = BrowserWindow.getFocusedWindow();
		window?.removeListener("unmaximize", handleMenuBarUnmaximize);
		window?.on("unmaximize", handleMenuBarUnmaximize);
		window?.removeListener("maximize", handleMenuBarMaximize);
		window?.on("maximize", handleMenuBarMaximize);
		tBarHandler = event;
	});

	//异步：监听打开磁吸工具栏窗口，默认贴右上侧：TODO
	ipcMain.on("IMGEDIT-TOOL-OPEN", function (event, arg) {
		if (toolWindow) {
			return;
		}
		const adsorbWindow = new AdsorbWindow(100, 230, "img_edit/tool");
		toolWindow = adsorbWindow.adsorbWin;
		toolWindow.on("closed", () => {
			toolWindow = undefined;
			windowHandler.reply("TOOLPAD-CLOSE-CALL");
		});
	});

	//异步：监听主动关闭工具箱子
	ipcMain.on("IMGEDIT-CLOSE-TOOLPAD", function (event, arg) {
		if (toolWindow) {
			toolWindow.close();
			toolWindow = undefined;
		}
	});

	//同步OCR
	ipcMain.on("IMGEDIT-OCR", async function (event, arg) {
		event.returnValue = await runPaddleOCR(arg.path);
	});
};

//监听window的unmaximize事件
const handleMenuBarUnmaximize = () => {
	tBarHandler.reply("unmaximize-call");
};

//监听window的unmaximize事件
const handleMenuBarMaximize = () => {
	tBarHandler.reply("maximize-call");
};
